package com.coalmine.api.util;

import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.LinkedHashMap;

@Slf4j
public class YamlUtil {

    public static final YamlUtil instance = new YamlUtil();
    private static LinkedHashMap<String, Object> ymlMap = new LinkedHashMap<>();

    static {
        Yaml yaml = new Yaml();
        try (InputStream in = YamlUtil.class.getClassLoader().getResourceAsStream("application.yml");) {
            ymlMap = yaml.load(in);
        } catch (Exception e) {
             log.error("load application.yml error-->",e.getMessage());
            e.printStackTrace();
        }
    }


    public  String getValue(String key) {
        String[] keys = key.split("[.]");
        LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) ymlMap.clone();
        int length = keys.length;
        Object resultValue = null;
        for (int i = 0; i < length; i++) {
            Object value = map.get(keys[i]);
            if (i < length - 1) {
                map = ((LinkedHashMap<String, Object>) value);
            } else {
                resultValue = value;
            }
        }
        return String.valueOf(resultValue);
    }

}